<template>
	<div class="container">
		<el-upload 
			class="upload-demo" 
			ref="upload" 
			:limit="1" 
			:on-exceed="fileExceed" 
			:action="action"
			:on-preview="handlePreview" 
			:on-change="fileChange"
			:on-remove="handleRemove" 
			:on-success="handleAvatarSuccess" 
			:auto-upload="false"
		>
			<el-button slot="trigger" color="#b24c5b" >选取图片</el-button>
		</el-upload>
	</div>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref } from "vue";
// 上传
let upload = ref(null);

// 后端上传接口
let action = "http://localhost:8957/commons/upload";
// 接收返回的图片名称
let returnPicName = ref<string>("no")
// 是否选择了图片
let isSelected = ref<boolean>(false);

/**
 * 修改上传成功后，后端返回的图片名称
 * @param res 成功的后端返回值
 */
function handleAvatarSuccess(res: string) {
	returnPicName.value = res;
}

// 手动上传
function submitUpload(){
	upload.value.submit();

}

function fileExceed() {
	ElMessage({
		message: '只能选择一张哦（想要继续请删除已存在的图片后在上传）',
	})
}

// 删除成功提示
function handleRemove(file:any) {
	ElMessage({
		message: `删除图片${file.name}成功!`,
    	type: 'success',
	});
	isSelected.value = false;
}

// 图片预览，点击图片
function handlePreview() {
	ElMessage({
		message: '别点啦~赶紧上传！',
	})
}

// 清空所选文件
function clearSelectFiles(){
	upload.value.clearFiles();
}

// 文件变化钩子
function fileChange(){
	isSelected.value = true;
}

defineExpose({
	submitUpload,
	clearSelectFiles,
	isSelected,
	returnPicName
})
</script>


<style scoped>
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}

.avatar-uploader .el-upload:hover {
	border-color: #b02035;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}

.avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>
